// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html
var CreatorHelper = require("CreatorHelper");
var UnitTools = require("UnitTools");
var User = require("User");
var Handler = require("Handler");
var Majiang = require("Chess").Majiang;
var NetWorkManager = require("NetWorkManager");

var HandAction = {
    Peng:1,
    AnGang:2,
    GuoluGang:3,
    MingGang:4
}
//声明：
//type 1表示自己 2表示其他位置
cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
        handCardsPfb:{
            default:[],
            type:cc.Prefab
        },
        hitCardsPfb:{
            default:[],
            type:cc.Prefab
        },
        gangpengPfb:{
            default:[],
            type:cc.Prefab
        },
        actionSelectPfb:cc.Prefab,
        actionImages:{
            default:[],
            type:cc.SpriteFrame
        },
        actionSplashPfb:cc.Prefab,
        splashImages:{
            default:[],
            type:cc.SpriteFrame
        },
        cardImages:cc.SpriteAtlas,
        gameScorePfb:cc.Prefab,
        scoreItemPfb:cc.Prefab,
        scorebqPfb:cc.Prefab,//标签pfb
        cardhuPfb:cc.Prefab,//最后的牌的标签
        titleMask:{
            default:[],
            type:cc.SpriteFrame
        },
        finalScorePfb:cc.Prefab,
        finalScoreItemPfb:cc.Prefab,
        finalScoreDetailPfb:cc.Prefab,
        waitingPfb:cc.Prefab,//等待的黑色界面
        jiesanPfb:cc.Prefab//解散界面
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.selfPos = 2;
        this.posCount = 4;
        this.gameStarted = false;//表示游戏是否开始
        this.headRoot = {};
        this.headSpUi = {};
        this.nameUi = {};
        this.scoreUi = {};
        this.raceScore = null;//最后服务器发送的最终数据
        this.selectaActionUi = cc.find("actionselectui",this.node);//动作选择UI
        for(var pos = 0;pos<this.posCount;pos++){
            this.headRoot[pos] = cc.find("headwig"+pos+"/head",this.node);
            this.headSpUi[pos] = cc.find("headwig"+pos+"/head/headframe/head",this.node);
            this.nameUi[pos] = cc.find("headwig"+pos+"/head/name",this.node);
            this.scoreUi[pos] = cc.find("headwig"+pos+"/head/score",this.node);
        }
        this.handCardsUi = cc.find("handcards",this.node);//手里牌的ui根节点
        this.hitCardsUi = cc.find("hitcards",this.node);//出牌的Ui根节点
        this.gangpegnCardsUi = cc.find("gangpengcards",this.node);//杠碰的牌
        this.gangpegnCardsUiBotttom = cc.find("gangpengcardsbottom",this.node);//杠碰的牌
        this.splashsUi = cc.find("splashs",this.node);//杠碰闪烁提示
        this.turnTime = cc.find("turntime",this.node);//指针
        this.pInfos = {};//保存玩家信息

        Handler.instance().logicCom = this;

        this.handCardsPos = this.createHandCardPos();
        this.hitCardsPos = this.createHitCardPos();
        this.gangpengCardsPos = this.createGangpegnCardPos();
        this.splashPos = this.createSplashPos();
        this.isRestore = false;//是否是在断线重连中
        this.selfHandCard = new Array(34);
        this.hitCards = {};
        for(var i = 0;i<34;i++) {
            this.selfHandCard[i] = {};//{11:{ui:}};
        }
        this.handCards = new Array(this.posCount);//[{cardIndex,ui}]
        this.clearToStart();

        //添加UI事件
        this.setbg = cc.find("setbg",this.node);//设置框
        CreatorHelper.setNodeClickEvent(this.setbg.getChildByName("jiesan"),function () {//添加点击解散按钮
            //发送消息给服务器，申请解散
            // this.showJiesan(1);
            // this.updateJiesan(0,"鸡蛋0",0);
            // this.updateJiesan(1,"鸡蛋1",1);
            // this.updateJiesan(2,"鸡蛋2",2);
            // this.updateJiesan(3,"鸡蛋3",0);
            this.setbg.active = false;
            if(this.gameStarted){
                NetWorkManager.onConnectedToGame(function (client) {//调用申请解散
                    client.proxy.askJiesan(function (data) {
                        cc.log(data);
                    })
                })
            }else{
                NetWorkManager.onConnectedToGame(function (client) {
                    client.proxy.jiesanDirect(function (data) {
                        cc.log(data);
                    })
                })
            }

        }.bind(this))


        this.onClose = function () {
            var bg = cc.instantiate(this.waitingPfb);
            this.node.addChild(bg);
            cc.log("游戏中断了");
            NetWorkManager.onConnectedToGame(function () {
                cc.log("再次连接到服务器")
                // bg.removeFromParent(true);
                // bg.destroy();
                cc.director.loadScene("game");//后面调试
                //清理界面，断线重连
            })
        }
        NetWorkManager.onClosedFromGame(this.onClose.bind(this));
    },
    clearToStart(){
        for(var pos = 0;pos<this.posCount;pos++) {
            this.headRoot[pos].active = false;
            this.nameUi[pos].getComponent(cc.Label).string = "";
            this.scoreUi[pos].getComponent(cc.Label).string = "";
            this.hitCards[pos] = {};
            var cards = this.handCards[pos] = new Array(14);
            cards.fill(null);
        }
    },
    clearToContinue(){
        this.handCardsUi.removeAllChildren(true);
        this.handCardsUi.destroyAllChildren();
        this.hitCardsUi.removeAllChildren(true);
        this.hitCardsUi.destroyAllChildren();
        this.gangpegnCardsUi.removeAllChildren(true);
        this.gangpegnCardsUi.destroyAllChildren();
        this.gangpegnCardsUiBotttom.removeAllChildren(true);
        this.gangpegnCardsUiBotttom.destroyAllChildren();
        this.selectaActionUi.removeAllChildren(true);
        this.selectaActionUi.destroyAllChildren();
        this.turnTime.active = false;

        this.selfHandCard = new Array(34);
        this.hitCards = {};
        for(var i = 0;i<34;i++) {
            this.selfHandCard[i] = {};//{11:{ui:}};
        }
        this.handCards = new Array(this.posCount);//[{cardIndex,ui}]
        for(var pos = 0;pos<this.posCount;pos++) {
            this.hitCards[pos] = {};
            var cards = this.handCards[pos] = new Array(14);
            cards.fill(null);
        }
    },
    createHandCardPos(){//创建所有位置手里牌的位置
        var posArray = new Array(this.posCount);
        posArray[0] = {startPos:{x:254,y:208},offset:{x:-40,y:0},lastOffset:{x:-20,y:0}};
        posArray[1] = {startPos:{x:-429,y:253},offset:{x:0,y:-29},lastOffset:{x:0,y:-20}};
        posArray[2] = {startPos:{x:-576,y:-347},offset:{x:82,y:0},lastOffset:{x:20,y:0}};
        posArray[3] = {startPos:{x:429,y:-193},offset:{x:0,y:29},lastOffset:{x:0,y:20}};

        var handCardsPos = new Array(this.posCount);
        for(var pos = 0;pos<this.posCount;pos++){
            var cardPos = new Array(14);
            handCardsPos[pos] = cardPos;
            for(var index = 0;index<14;index++){
                var position = cardPos[index] = {};
                var config = posArray[pos];
                position.x = config.startPos.x + index * config.offset.x;
                position.y = config.startPos.y + index * config.offset.y;

                if(index == 13){//最后摸的牌
                    position.x+= config.lastOffset.x;
                    position.y+= config.lastOffset.y;
                }
            }
        }
        return handCardsPos;
    },
    createHitCardPos(){//创建所有位置打出去牌的位置
        var posArray = new Array(this.posCount);
        posArray[0] = {startPos:{x:175,y:70},offset:{x:-35,y:0},lineOffset:{x:0,y:42}};
        posArray[1] = {startPos:{x:-180,y:150},offset:{x:0,y:-29},lineOffset:{x:-47,y:0}};
        posArray[2] = {startPos:{x:-175,y:-80},offset:{x:35,y:0},lineOffset:{x:0,y:-41}};
        posArray[3] = {startPos:{x:180,y:-150},offset:{x:0,y:29},lineOffset:{x:47,y:0}};
        var hitCardsPos = new Array(this.posCount);
        for(var pos = 0;pos<this.posCount;pos++){
            var cardPos = new Array(25);
            hitCardsPos[pos] = cardPos;
            for(var index = 0;index<25;index++){
                var position = cardPos[index] = {};
                var config = posArray[pos];
                var line = parseInt(index/10);
                var lineIndex = index%10;
                position.x = config.startPos.x + lineIndex * config.offset.x + config.lineOffset.x * line;
                position.y = config.startPos.y + lineIndex * config.offset.y + config.lineOffset.y * line;

            }
        }
        return hitCardsPos;
    },
    createGangpegnCardPos(){//创建杠碰牌的位置
        var posArray = new Array(this.posCount);
        posArray[0] = {startPos:{x:294,y:208},offset:{x:-130,y:0}};
        posArray[1] = {startPos:{x:-449,y:253},offset:{x:0,y:-98}};
        posArray[2] = {startPos:{x:-576,y:-347},offset:{x:200,y:0}};
        posArray[3] = {startPos:{x:455,y:-193},offset:{x:0,y:98}};
        var gangpengPos = {};
        for(var pos = 0;pos<this.posCount;pos++){
            var positions = gangpengPos[pos] = [];
            for(var i = 0;i<4;i++){
                var position = {};
                position.x = posArray[pos].startPos.x +posArray[pos].offset.x * i;
                position.y = posArray[pos].startPos.y +posArray[pos].offset.y * i;
                positions.push(position);
            }
        }
        return gangpengPos;
    },
    createSplashPos(){
        var posArray = new Array(this.posCount);
        posArray[0] = {x:0,y:150};
        posArray[1] = {x:-400,y:0};
        posArray[2] = {x:0,y:-150};
        posArray[3] = {x:400,y:0};

        return posArray;
    },
    createHandCardUi(pos,cardIndex){
        var pfb = this.handCardsPfb[pos];
        var cardUi = cc.instantiate(pfb);
        if(pos == 2){
            //修改sprteFrame
            var sp = this.cardImages.getSpriteFrame(Majiang.smCard(cardIndex))
            cardUi.getComponent(cc.Sprite).spriteFrame = sp;
        }
        return cardUi;
    },
    createHitCardUi(pos,cardIndex){
        var preStr = ["h","l","h","r"];
        var pfb = this.hitCardsPfb[pos];
        var cardUi = cc.instantiate(pfb);
        var sp = this.cardImages.getSpriteFrame(preStr[pos]+Majiang.smCard(cardIndex));
        cardUi.getComponent(cc.Sprite).spriteFrame = sp;
        return cardUi;
    },
    createGangpengCardUi(pos,cardIndex,type){//1 表示碰  2表示杠
        var preStr = ["h","l","h","r"];
        var gangpengUi = cc.instantiate(this.gangpengPfb[pos]);
        var cards = gangpengUi.children;
        for(var i = 0;i<cards.length;i++){
            var card = cards[i];
            var sp = this.cardImages.getSpriteFrame(preStr[pos]+Majiang.smCard(cardIndex))
            card.getComponent(cc.Sprite).spriteFrame = sp;
        }
        type == 1?cards[3].active = false:cards[3].active = true;
        return gangpengUi;
    },
    addHitCardUi(pos,cardIndex){
        var hitCardUi = this.createHitCardUi(pos,cardIndex);
        //设置位置
        var index = Object.keys(this.hitCards[pos]).length;
        var postion = this.hitCardsPos[pos][index];
        hitCardUi.x = postion.x;hitCardUi.y = postion.y;
        var zIndex = 0;
        if(pos == 0 || pos == 3){
            zIndex = 25 - index;
        }
        if(pos == 1 || pos == 2){
            zIndex = index;
        }
        hitCardUi.setLocalZOrder(zIndex);
        this.hitCardsUi.addChild(hitCardUi);
        this.hitCards[pos][cardIndex] = {ui:hitCardUi,cardIndex:cardIndex};
    },
    addGangpengCardUi(pos,cardIndex,type,index){
        var count = 0;
        for(var idx in this.gangpegnCardsUi.children){
            var ui = this.gangpegnCardsUi.children[idx];
            if(ui.meta.pos == pos)count+=1;
        }

        var gangpengUi = this.createGangpengCardUi(pos,cardIndex,type);
        gangpengUi.meta = {};
        gangpengUi.meta.tIndex = Majiang.tIndex(cardIndex);
        gangpengUi.meta.pos = pos;
        var position = this.gangpengCardsPos[pos][count];
        gangpengUi.x = position.x;
        gangpengUi.y = position.y;
        pos == 3 ?this.gangpegnCardsUiBotttom.addChild(gangpengUi):this.gangpegnCardsUi.addChild(gangpengUi);
    },
    addSplashUi(pos,type){
        if(this.isRestore)return;
        var map = {1:0,2:1,3:1,4:1,5:2,6:2};
        var splashsUi = cc.instantiate(this.actionSplashPfb);
        splashsUi.getComponent(cc.Sprite).spriteFrame = this.splashImages[map[type]];
        var position = this.splashPos[pos];
        splashsUi.x = position.x;
        splashsUi.y = position.y;
        this.splashsUi.addChild(splashsUi);
        splashsUi.getComponent(cc.Animation).on("finished",function () {
            splashsUi.removeFromParent(true);
        })
    },
    getScreenPos(selfLogicPos,logicPos){
        var myPos = selfLogicPos;
        var delta = new Number(myPos) - 2;
        var screenPos = new Number(logicPos) - delta;
        screenPos =  screenPos<0?4+screenPos:screenPos;
        screenPos =  screenPos>=4?screenPos-4:screenPos;
        return screenPos;
    },

    showHead(pId,scrPos,imgUrl,name){
        this.headRoot[scrPos].active = true;
        var sp = this.headSpUi[scrPos].getComponent(cc.Sprite);
        var nameLab = this.nameUi[scrPos].getComponent(cc.Label);
        CreatorHelper.changeSpriteFrameWithServerUrl(sp,{url:imgUrl,type:"png"});
        nameLab.string = name;
        var info = UnitTools.getOrCreateJsonInJson(pId,this.pInfos);
        info.pos = scrPos;
    },
    hideHead(pId){
        var info = this.pInfos[pId];
        if(UnitTools.isNullOrUndefined(info))return;
        var pos = info.pos;
        this.headRoot[pos].active = false;
        this.nameUi[pos].getComponent(cc.Label).string = "";
        this.scoreUi[pos].getComponent(cc.Label).string = "";
    },
    adjustSelfHandCard(){
        var cardCount = 0;
        for(var i = 33;i>=0;i--){
            var cards = this.selfHandCard[i];
            for(var cardIndex in cards){
                cardIndex = parseInt(cardIndex);
                var ui = cards[cardIndex].ui;
                var index = 12 - cardCount;
                cardCount+=1;
                var pos = this.handCardsPos[2][index];
                ui.x = pos.x;ui.y = pos.y;
            }
        }
    },
    adjustHandCard(pos){
        if(this.handCards[pos][13] != null){
            var card = this.handCards[pos][13];
            for(var idx in this.handCards[pos]){
                if(this.handCards[pos][idx] == null){
                    this.handCards[pos][idx] = card;
                    this.handCards[pos][13] = null;
                    break;
                }
            }
        }
        var handCards = this.handCards[pos];
        var startIndex = 12;
        for(var idx in handCards){
            var card = handCards[idx];
            if(card == null)continue;
            var position = this.handCardsPos[pos][startIndex];
            card.ui.x = position.x;
            card.ui.y = position.y;
            card.ui.setLocalZOrder(pos == 3?12 - startIndex:startIndex);
            startIndex-=1;
        }
    },
    touchCard(scrPos,cardIndex,type){
        var cardUi = this.createHandCardUi(scrPos,cardIndex);
        var pos = this.handCardsPos[scrPos][13];
        cardUi.x = pos.x;cardUi.y = pos.y;
        this.handCardsUi.addChild(cardUi);
        var handCars = this.handCards[scrPos];
        handCars[13] = {cardIndex:cardIndex,ui:cardUi};
        if(type == 1){
            var tIndex = Majiang.tIndex(cardIndex);
            this.selfHandCard[tIndex][cardIndex] = {ui:cardUi};
            this.bindCardEvt(cardIndex,cardUi);
        }
    },
    removeHandCardsAndAdjust(pos,cardIndexs){//删除手里的牌，并进行整理
        var type = pos == 2?1:2;
        for(var idx in cardIndexs){
            var cardIndex = cardIndexs[idx];
            if(type == 1){
                var tIndex = Majiang.tIndex(cardIndex);
                var ui = this.selfHandCard[tIndex][cardIndex].ui;
                ui.removeFromParent(true);
                delete  this.selfHandCard[tIndex][cardIndex];

            }else  if(type == 2){
                var handCards = this.handCards[pos];
                for(var idx in handCards){
                    var card = handCards[idx];
                    if(card == null)continue;
                    card.ui.removeFromParent(true);
                    handCards[idx] = null;
                    break;
                }
            }
        }

        type == 1?this.adjustSelfHandCard():this.adjustHandCard(pos);

    },
    turn(scrPos,time = 20){
         if(this.timeSche)this.unschedule(this.timeSche);
         var rotations = [180,90,0,-90];
         this.turnTime.active = true;
         this.turnTime.getChildByName("point").rotation = rotations[scrPos];
         //超时tick
        this.turnTime.getChildByName("text").getComponent(cc.Label).string = time;

        this.timeSche = function () {
            time-=1;
            this.turnTime.getChildByName("text").getComponent(cc.Label).string = time;
        }.bind(this)
        this.schedule(this.timeSche,1,19,0);
    },
    hitCard(scrPos,cardIndex,type){
        this.addHitCardUi(scrPos,cardIndex);
        if(type == 1){
            var tIndex = Majiang.tIndex(cardIndex);
            var ui = this.selfHandCard[tIndex][cardIndex].ui;
            ui.removeFromParent(true);
            delete  this.selfHandCard[tIndex][cardIndex];
            this.adjustSelfHandCard();
        }else  if(type == 2){
            var handCards = this.handCards[scrPos];
            for(var idx in handCards){
                var card = handCards[idx];
                if(card == null)continue;
                card.ui.removeFromParent(true);
                handCards[idx] = null;
                break;
            }
            this.adjustHandCard(scrPos);
        }
    },
    bindCardEvt(cardIndex,cardUi){
        var self = this;
        cardUi.cardIndex = cardIndex;
        cardUi.popUp = false;
        CreatorHelper.setNodeClickEvent(cardUi,function () {
            if(cardUi.popUp == true){
                //出牌
                cc.log("出牌:"+cardIndex);
                NetWorkManager.onConnectedToGame(function (client) {
                    var data = {};
                    data.cardIndex = cardIndex;
                    data.actionId = self.actionId;
                    client.proxy.hitCard(data,function (data) {
                        cc.log(data);
                    })
                })
            }else{//自己弹起，其他的牌都下去
                for(var tIndex in this.selfHandCard){
                    var cards = this.selfHandCard[tIndex];
                    for(var cIdx in cards){
                        var ui = cards[cIdx].ui;
                        if(!ui.popUp)continue;
                        ui.y-=40;
                        ui.popUp = false;
                    }
                }
                cardUi.y+=40;
                cardUi.popUp = true;
            }
        }.bind(this))
    },
    showActionSelectUi(actions){
        var self = this;
        var selectAction = function (actionType,cardIndex) {//调用服务器action选择
            NetWorkManager.onConnectedToGame(function (client) {
                var data = {};data.actionType = actionType;data.cardIndex = cardIndex;data.actionId = self.actionId;
                client.proxy.selectAction(data,function (data) {
                    cc.log("选择结果");
                    cc.log(data);
                    self.selectaActionUi.removeAllChildren(true);
                })
            })
        }
        this.selectaActionUi.active = true;
        this.selectaActionUi.removeAllChildren(true);
        var map = {1:1,2:2,3:2,4:2,5:3,6:3};
        //添加过
        var passUi = cc.instantiate(this.actionSelectPfb);
        passUi.getComponent(cc.Sprite).spriteFrame = this.actionImages[0];
        passUi.getChildByName("card").active = false;
        this.selectaActionUi.addChild(passUi);
        CreatorHelper.setNodeClickEvent(passUi,function () {
            cc.log("选择了Action:");
            cc.log("actionType:"+0);
            cc.log("tIndex:"+0);
            selectAction(0,0);
        })

        for(var actionType in actions){
            var action = actions[actionType];
            var details = [];
            if(!(action instanceof Array)){
                details.push(action);
            }else{
                details = action;
            }
            for(var idx in details){
                var detail = details[idx];//pos tIndex
                var cardIndex = detail.cardIndex;
                var selectUi = cc.instantiate(this.actionSelectPfb);
                //修改图标 修改麻将
                selectUi.getComponent(cc.Sprite).spriteFrame = this.actionImages[map[actionType]];
                selectUi.getChildByName("card").getComponent(cc.Sprite).spriteFrame = this.cardImages.getSpriteFrame(Majiang.smCard(cardIndex));
                this.selectaActionUi.addChild(selectUi);
                CreatorHelper.setNodeClickEvent(selectUi,function (actionType,cardIndex) {
                    cc.log("选择了Action:");
                    cc.log("actionType:"+actionType);
                    cc.log("cardIndex:"+cardIndex);
                    selectAction(actionType,cardIndex);
                }.bind(this,actionType,cardIndex))
            }
        }
    },
    handleDoAction(data){
        //思路碰：
        //0.显示碰的Splash
        //1.打出去的牌删掉
        //2.自己手里的两张牌删掉
        //3.自己显示碰的牌
        //4.重新整理自己手里的牌
        this.selectaActionUi.active = false;
        var actionType = data.actionType;
        var pos = data.pos;
        var hitPos = data.hitPos;
        var scrPos = this.getScreenPos(User.pos,pos);//屏幕位置
        var hitScrPos = this.getScreenPos(User.pos,hitPos);//打牌人的屏幕位置
        var cardIndex = data.hitIndex;
        var cardIndexs = data.cardIndexs;
        if(actionType == HandAction.Peng){//处理碰
            this.addSplashUi(scrPos,actionType);//0
            var hitUi = this.hitCards[hitScrPos][cardIndex].ui;//1
            hitUi.removeFromParent(true);
            delete this.hitCards[hitScrPos][cardIndex];
            this.removeHandCardsAndAdjust(scrPos,cardIndexs);//2
            this.addGangpengCardUi(scrPos,cardIndex,actionType,this.gangpegnCardsUi.children.length);//3
        }else if(actionType == HandAction.AnGang){//处理暗杠
            var cardIndex = data.cardIndex;
            this.addSplashUi(scrPos,actionType);
            this.removeHandCardsAndAdjust(scrPos,cardIndexs);//2
            this.addGangpengCardUi(scrPos,cardIndex,actionType,this.gangpegnCardsUi.children.length);//3
        }else if(actionType == HandAction.MingGang){//处理明杠
            this.addSplashUi(scrPos,actionType);//0
            var hitUi = this.hitCards[hitScrPos][cardIndex].ui;//1
            hitUi.removeFromParent(true);
            delete this.hitCards[hitScrPos][cardIndex];
            this.removeHandCardsAndAdjust(scrPos,cardIndexs);//2
            this.addGangpengCardUi(scrPos,cardIndex,actionType,this.gangpegnCardsUi.children.length);//3
        }else if(actionType == HandAction.GuoluGang){//处理过路杠
            var cardIndex = data.cardIndex;
            var uis = this.gangpegnCardsUi.children;
            this.addSplashUi(scrPos,actionType);
            this.removeHandCardsAndAdjust(scrPos,cardIndexs);
            for(var idx in uis){
                var ui = uis[idx];
                if(ui.meta.tIndex == Majiang.tIndex(cardIndex)){
                    ui.children[3].active = true;
                    break;
                }
            }
        }
    },
    handleHu(data){
        this.selectaActionUi.removeAllChildren(true);
        this.selectaActionUi.destroyAllChildren();

        var posHuType = data.posHuType;
        for(var pos in posHuType){
            var actionType = posHuType[pos];
            var scrPos = this.getScreenPos(User.pos,pos);//屏幕位置
            this.addSplashUi(scrPos,actionType);//显示出胡牌
        }
        this.scheduleOnce(function () {
            this.showGmScore(data.zhuangPos,data.posHuType,data.paoPos,data.score,data.posNames,data.huCardIndex,data.posHandCards,data.posActionCards,data.huSpecals);
        }.bind(this),2);

    },
    showGmScore(zhuangPos,huPosAndType,paoPos,posScores,posNames,huCardIndex,posHandCards,posActionCards,huSpecals){//显示游戏结算界面 posActionCards {0:[{1:{tIndex:2,hitPos:3,pos:5}}，，，]}
        var self = this;
        var specalName = {0:"清一色"};
        var addStyle = function (styleRoot,styleName) {
            var biaoqiangNode = cc.instantiate(this.scorebqPfb);
            styleRoot.addChild(biaoqiangNode);
            var nameNode = cc.find("name",biaoqiangNode);
            nameNode.getComponent(cc.Label).string = styleName;
        }.bind(this);
        var scoreUi = cc.instantiate(this.gameScorePfb);
        this.node.addChild(scoreUi);
        var titleNode = cc.find("title",scoreUi);
        if(Object.keys(huPosAndType).length == 0){//流局
            titleNode.getComponent(cc.Sprite).spriteFrame = this.titleMask[0];
        }else if(posScores[User.pos] > 0){
            titleNode.getComponent(cc.Sprite).spriteFrame = this.titleMask[1];
        }else if(posScores[User.pos] <=0){
            titleNode.getComponent(cc.Sprite).spriteFrame = this.titleMask[2];
        }
        var actionTimes = {};//actionType 0表示点杠  2表示暗杠  3表示过路杠 4表示明杠
        var scoreItemsNode = cc.find("scoreitems",scoreUi);
        scoreItemsNode.removeAllChildren(true);
        scoreItemsNode.destroyAllChildren();
        for(var pos = 0;pos<this.posCount;pos++) {
            var scrPos = this.getScreenPos(User.pos, pos);
            var scoreItem = cc.instantiate(this.scoreItemPfb);
            scoreItemsNode.addChild(scoreItem);
            var zhuangNode = cc.find("zhuang", scoreItem);
            zhuangNode.active = false;
            if (pos == zhuangPos) zhuangNode.active = true;//显示庄
            var nameNode = cc.find("name", scoreItem);
            nameNode.getComponent(cc.Label).string = posNames[pos];//显示名字
            var scoreNode = cc.find("score", scoreItem);
            scoreNode.getComponent(cc.Label).string = posScores[pos];//显示分数
            var huMaskNode = cc.find("humask", scoreItem);
            huMaskNode.active = false;
            var styleNode = cc.find("style", scoreItem);
            styleNode.destroyAllChildren();
            var huType = huPosAndType[pos];
            if (!UnitTools.isNullOrUndefined(huType)) {//显示胡mask
                var styleName = huType == 5 ? "接炮" : "自摸";
                addStyle(styleNode, styleName);
                huMaskNode.active = true;
            } else if (paoPos != null && paoPos == pos) addStyle(styleNode, "点炮");
            var addActionTime = function (pos,actionType) {
                if(UnitTools.isNullOrUndefined(actionTimes[pos]))actionTimes[pos] = {};
                if(UnitTools.isNullOrUndefined(actionTimes[pos][actionType]))actionTimes[pos][actionType] = 0;
                actionTimes[pos][actionType]+=1;
            }
            var huSpecal = huSpecals[pos];
            for(var idxS in huSpecal){
                addStyle(styleNode,specalName[huSpecal[idxS]]);
            }

            var actionCards = posActionCards[pos];
            var handCards = posHandCards[pos];
            var cardStartX = 0;//当前牌的X位置
            var cardOffset = 55;//普通牌的offset
            var pengOffset = 170;//碰的offset
            var gangOffset = 225;//杠的offset
            var huCardOffset = 20;//最后胡的牌的offset

            var mjrootNode = cc.find("mjroot",scoreItem);
            mjrootNode.destroyAllChildren();
            for(var idx in actionCards){
                var acards = actionCards[idx];
                var actionType = idx;
                var cardIndex = Majiang.cards[acards.tIndex];
                var hitPos = acards.hitPos;
                if(actionType == HandAction.Peng){//显示3牌了
                    for(var count = 0;count<3;count++){
                        var cardUi = this.createHitCardUi(2,cardIndex);
                        cardUi.x = -12;
                        cardUi.y = 60;
                        cardUi.scale = 1;
                        mjrootNode.addChild(cardUi);
                        cardUi.x+= cardStartX+ cardOffset * count;
                    }
                    cardStartX+=pengOffset;
                }else if (actionType == HandAction.AnGang){
                    for(var count = 0;count<4;count++){
                        var cardUi = this.createHitCardUi(2,cardIndex);
                        cardUi.x = -12;
                        cardUi.y = 60;
                        cardUi.scale = 1;
                        mjrootNode.addChild(cardUi);
                        cardUi.x+= cardStartX+ cardOffset * count;
                    }
                    addActionTime(pos,HandAction.AnGang);
                    cardStartX+=gangOffset;
                }else if(actionType == HandAction.MingGang){
                    for(var count = 0;count<4;count++){
                        var cardUi = this.createHitCardUi(2,cardIndex);
                        cardUi.x = -12;
                        cardUi.y = 60;
                        cardUi.scale = 1;
                        mjrootNode.addChild(cardUi);
                        cardUi.x+= cardStartX+ cardOffset * count;
                    }
                    addActionTime(hitPos,0);
                    addActionTime(pos,HandAction.MingGang);
                    cardStartX+=gangOffset;
                }else if(actionType == HandAction.GuoluGang){
                    for(var count = 0;count<4;count++){
                        var cardUi = this.createHitCardUi(2,cardIndex);
                        cardUi.x = -12;
                        cardUi.y = 60;
                        cardUi.scale = 1;
                        mjrootNode.addChild(cardUi);
                        cardUi.x+= cardStartX+ cardOffset * count;

                    }
                    addActionTime(hitPos,0);
                    addActionTime(pos,HandAction.GuoluGang);
                    cardStartX+=gangOffset;
                }
            }

            var count = 0;
            delete  handCards[huCardIndex];
            for(var cardIndex in handCards){//显示手牌
                var cardUi = this.createHitCardUi(2,cardIndex);
                cardUi.x = -12;
                cardUi.y = 60;
                cardUi.scale = 1;
                mjrootNode.addChild(cardUi);
                cardUi.x+=cardStartX;
                cardStartX+=cardOffset;
                count+=1;
            }
            //显示胡牌
            if(!UnitTools.isNullOrUndefined(huType)){//自己胡，显示最后胡的牌
                var cardUi = this.createHitCardUi(2,huCardIndex);
                cardUi.x = -12;
                cardUi.y = 60;
                cardUi.scale = 1;
                mjrootNode.addChild(cardUi);
                cardUi.x+= cardStartX+huCardOffset;
                var hbqUi = cc.instantiate(this.cardhuPfb);
                mjrootNode.addChild(hbqUi);
                hbqUi.x += cardStartX+huCardOffset;
            }
        }
        for(var pos = 0;pos<this.posCount;pos++){
            var aTimeNode = cc.find("actiontimes",scoreItemsNode.children[pos]);//动作次数
            aTimeNode.getComponent(cc.Label).string = "";
            var aTimeName = {0:"点杠",2:"暗杠",3:"明杠",4:"过路杠"}
            var aTimes = actionTimes[pos];
            for(var aType in aTimes){
                var aTName = aTimeName[aType];
                var aTime = aTimes[aType];
                aTimeNode.getComponent(cc.Label).string+=aTName+"×"+aTime+" ";
            }
        }

        //添加点击继续事件
        var goonbn = scoreUi.getChildByName("goonbn");
        CreatorHelper.setNodeClickEvent(goonbn,function () {
            scoreUi.removeFromParent(true);
            scoreUi.destroy();
            if(self.raceScore == null){//继续游戏了
                //继续游戏，清空界面
                self.clearToContinue();
                NetWorkManager.onConnectedToGame(function (client) {
                    client.proxy.ready(true,function (data) {
                        cc.log(data);
                    })
                })
            }else {//结束了
                self.showFinalScore(self.raceScore.posScores,self.raceScore.posNames);
            }
        })
    },
    showFinalScore(posScores,posNameAndHeadUrl){
        var finalScoreUi = cc.instantiate(this.finalScorePfb);
        this.node.addChild(finalScoreUi);
        var detailsUi = cc.find("details",finalScoreUi);
        detailsUi.removeAllChildren(true);
        detailsUi.destroyAllChildren();
        for(var pos in posScores){
            var scores = posScores[pos];
            var name = posNameAndHeadUrl[pos].name;
            var headUrl = posNameAndHeadUrl[pos].headUrl;
            var scoreItemUi = cc.instantiate(this.finalScoreItemPfb);
            detailsUi.addChild(scoreItemUi);
            var headSp = cc.find("head",scoreItemUi).getComponent(cc.Sprite);
            CreatorHelper.changeSpriteFrameWithServerUrl(headSp,{url:headUrl,type:"png"});
            var nameLab = cc.find("name",scoreItemUi).getComponent(cc.Label);
            nameLab.string = name;
            var allScore = 0;
            var scoresUi = cc.find("detailscroll/view/content",scoreItemUi);
            scoresUi.removeAllChildren(true);
            scoresUi.destroyAllChildren();
            for(var idx in scores){
                var score = scores[idx];
                var scoreUi = cc.instantiate(this.finalScoreDetailPfb);
                scoresUi.addChild(scoreUi);
                scoreUi.getComponent(cc.Label).string = "第"+(parseInt(idx)+1)+"局 "+score;
                allScore+=score;
            }
            var finalScoreUi = cc.find("score",scoreItemUi);
            finalScoreUi.getComponent(cc.Label).string = allScore;
        }
    },
    showJiesan(pos){//显示解散框,根据参数，来决定是否显示解散操作
        var ui = cc.find("jiesanbg",this.node);
        if(ui){
            ui.removeFromParent(true);
            ui.destroy();
        }
        ui = cc.instantiate(this.jiesanPfb);
        this.node.addChild(ui);
        var agreeBn = ui.getChildByName("tongyi");
        var jujueBn = ui.getChildByName("jujue");
        if(User.pos == pos){//自己，隐藏操作按钮
            agreeBn.active = false;
            jujueBn.active = false;
        }
        CreatorHelper.setNodeClickEvent(agreeBn,function () {
            NetWorkManager.onConnectedToGame(function (client) {
                client.proxy.doJiesanAction(true,function (data) {
                    cc.log(data);
                })
            })
            agreeBn.active = false;
            jujueBn.active = false;
        })
        CreatorHelper.setNodeClickEvent(jujueBn,function () {
            NetWorkManager.onConnectedToGame(function (client) {
                client.proxy.doJiesanAction(false,function (data) {
                    cc.log(data);
                })
            })
            agreeBn.active = false;
            jujueBn.active = false;
        })
        //添加倒计时
        var time = 60;
        var cloclText = cc.find("clockbg/text",ui).getComponent(cc.Label);
        cloclText.string = time;
        cloclText.schedule(function () {
            time-=1;
            cloclText.string = time;
        },1,59);

    },
    updateJiesan(pos,name,state){//更新解散界面状态 state 0表示 等待中 1表示同意 2表示拒绝
        var stateMap = {0:"选择中",1:"同意",2:"拒绝"};
        var ui = cc.find("jiesanbg",this.node);
        var names = ui.getChildByName("names");
        var states = ui.getChildByName("states");
        names.children[pos].getComponent(cc.Label).string = name;
        states.children[pos].getComponent(cc.Label).string = stateMap[state];
    },
    hideJiesan(){
        var ui = cc.find("jiesanbg",this.node);
        if(ui){
            ui.removeFromParent(true);
            ui.destroy();
        }
    },
    showRoomId(roomId){
        let roomIdLab = cc.find("gmtitle/roomId",this.node).getComponent(cc.Label);
        roomIdLab.string = "房间号:"+roomId;
    },
    showJiesanOrBack(state){//0表示显示解散 1表示显示返回
        var jiesanBn = cc.find("jiesanbn",this.node);
        var backBn = cc.find("fanhuibn",this.node);
        if(state == 0)jiesanBn.active = true;
        if(state == 1)backBn.active = true;
        if(state == 3){
            jiesanBn.active = false;
            backBn.active = false;
        }
        CreatorHelper.setNodeClickEvent(jiesanBn,function () {
            NetWorkManager.onConnectedToGame(function (client) {
                client.proxy.jiesanDirect(function (data) {
                    cc.log(data);
                })
            })
        })
        CreatorHelper.setNodeClickEvent(backBn,function () {
            NetWorkManager.onConnectedToGame(function (client) {
                client.proxy.backToHall(function (data) {
                    cc.log(data);
                })
            })
        })
    },
    normalStart(){
        //显示头像
        var self = this;
        var inRoomInfo = User.loginToGameData.inRoomInfo;
        cc.log("gameLogic->normalStart->loginToGameData:%o",User.loginToGameData);
        var heads = inRoomInfo.heads;
        User.playerId = inRoomInfo.playerId;
        User.pos = inRoomInfo.pos;
        UnitTools.forEach(heads,function (pos,pInfo) {
            self.showHead(pInfo.playerId,self.getScreenPos(User.pos,pos),pInfo.headimgurl,pInfo.nickname);
        })
        this.showRoomId(inRoomInfo.roomId);
        var frames = inRoomInfo.frames;

        //显示解散或者返回按钮
        if(inRoomInfo.createId == User.playerId){//显示解散按钮
            this.showJiesanOrBack(0);
        }else{//显示返回按钮
            this.showJiesanOrBack(1);
        }

        //处理frames里的消息(历史消息)
        for(var idx in frames){
            this.isRestore = true;//标识，当前处于断线重连中
            var frame = frames[idx];
            Handler.instance()["handle"+frame.eventName](frame.data);
        }
        this.isRestore = false;
        //处理，消息队列里的消息
    },
    start () {
        this.normalStart();
        //this.test();
    },
    test(){
        //----------------头像测试-------------------------
        this.showHead(2,0,"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg","鸡蛋");
        this.showHead(3,1,"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg","鸡蛋");
        this.showHead(4,2,"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg","鸡蛋");
        this.showHead(5,3,"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg","鸡蛋");

        //-----------------手里牌测试----------------------

        for(var i = 0;i<14;i++){
            var cardIndex = Majiang.cards[i];
            var cardUi = this.createHandCardUi(2,cardIndex);
            var pos = this.handCardsPos[2][i];
            cardUi.x = pos.x;cardUi.y = pos.y;
            this.handCardsUi.addChild(cardUi);
            var tIndex = Majiang.tIndex(cardIndex);
            this.selfHandCard[tIndex][''+cardIndex] = {ui:cardUi};
            this.bindCardEvt(cardIndex,cardUi);

            var cardUi = this.createHandCardUi(0,19);
            var pos = this.handCardsPos[0][i];
            cardUi.x = pos.x;cardUi.y = pos.y;
            this.handCardsUi.addChild(cardUi);

            var cardUi = this.createHandCardUi(1,19);
            var pos = this.handCardsPos[1][i];
            cardUi.x = pos.x;cardUi.y = pos.y;
            this.handCardsUi.addChild(cardUi);


            var cardUi = this.createHandCardUi(3,19);
            var pos = this.handCardsPos[3][i];
            cardUi.x = pos.x;cardUi.y = pos.y;
            cardUi.setLocalZOrder(14-i);
            this.handCardsUi.addChild(cardUi);
        }

        //-----------------打牌测试----------------------
        for(var i = 0;i<25;i++){
            var randomIndex = UnitTools.random(0,Majiang.cards.length-1);
            var cardIndex = Majiang.cards[randomIndex];
            for(var pos = 0;pos < this.posCount;pos++){
                this.addHitCardUi(pos,cardIndex);
            }
        }

        //-----------------action选择测试--------------------
        var actions = {};
        actions[1] = {pos:2,tIndex:0};//创造了一个碰
        actions[2] = [{pos:2,tIndex:1},{pos:2,tIndex:2}];
        this.showActionSelectUi(actions);

        //---------------杠碰牌测试--------------------
        for(var pos = 0;pos<4;pos++){
            for(var i = 0;i<4;i++){
                var randomIndex = UnitTools.random(0,Majiang.cards.length-1);
                var cardIndex = Majiang.cards[randomIndex];
                this.addGangpengCardUi(pos,cardIndex,2,i);
            }
        }

        //---------------spash测试--------------------
        for(var pos = 0;pos<4;pos++){
           this.addSplashUi(pos,1);
        }

        //--------------最后分数显示测试-------------------
        User.pos = 2;
        var zhuangPos = 2;
        var huPosAndType = {2:5};
        var paoPos = 3;
        var posScores = {0:0,1:0,2:2,3:-2};
        var posName = {0:"李鸡蛋0",1:"李鸡蛋1",2:"李鸡蛋2",3:"李鸡蛋3"};
        var posHandCards = {
            0:{ 11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1,19:1},
            1:{ 11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1},
            2:{ 11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1,19:1,21:1,22:1,23:1},
            3:{ 11:1,12:1,13:1,14:1,15:1,16:1,17:1,18:1},
        }
        var posActionCards = {
            0:{1:{tIndex:17}},
            1:{3:{tIndex:18,hitPos:2}},
            3:{4:{tIndex:19,hitPos:1}}};

        //this.showGmScore(zhuangPos,huPosAndType,paoPos,posScores,posName,41,posHandCards,posActionCards,{});

        //---------------最终分数显示---------------------
        var posScores = {0:[0,1,2,3,4,5,6,7,8],1:[0,1,2,3,4,5,6,7,8],2:[0,1,2,3,4,5,6,7,8],3:[0,1,2,3,4,5,6,7,8]}
        var posName = {0:{name:"李鸡蛋0",headUrl:"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg"},
            1:{name:"李鸡蛋1",headUrl:"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg"},
            2:{name:"李鸡蛋2",headUrl:"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg"},
            3:{name:"李鸡蛋3",headUrl:"http://i4.fuimg.com/583278/00e2ef22ec67b9b0.jpg"}};
        //this.showFinalScore(posScores,posName);

        //this.clearToContinue();

    },
    update (dt) {
        for(var idx  in Handler.instance().eventQueue){
            var frame = Handler.instance().eventQueue[idx];
            Handler.instance()["handle"+frame.evetnName](frame.data);
        }
        Handler.instance().eventQueue = [];//清空消息队列
    },
    onDestroy(){
        NetWorkManager.offClosedFromGame(this.onClose.bind(this));
        NetWorkManager.clearGameService();
    }
});
